<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\finance;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\lists\ListsExcelInterface;
use app\common\lists\ListsExtendInterface;
use app\common\model\finance\TransactionRecord;
use app\common\lists\ListsSearchInterface;
use think\facade\Db;


/**
 * transaction列表
 * Class TransactionRecordLists
 * @package app\adminapi\listsfinance
 */
class TransactionRecordLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExcelInterface, ListsExtendInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2025/04/08 19:39
     */
    public function setSearch(): array
    {
        return [
            '=' => ['group_id', 'card_bin'],
        ];
    }

    public function queryWhere()
    {

        $where = [];

        // 卡号
        if (isset($this->params['card_id']) && $this->params['card_id']) {
            if (strlen($this->params['card_id']) == 4) {
                $where[] = function ($query) {
                    $query->whereRaw('RIGHT(masked_card_number, 4) = ?', [$this->params['card_id']]);
                };
            } else {
                $where[] = ['card_id', '=', $this->params['card_id']];
            }
        }


        // 开始时间
        if (isset($this->params['create_time_start']) && isset($this->params['create_time_end']) && $this->params['create_time_start'] && $this->params['create_time_end']) {
            $where[] = [
                'transaction_date', 'between', [$this->params['create_time_start'], $this->params['create_time_end']]
            ];
        }
        // 交易状态
        if (isset($this->params['status']) && $this->params['status']) {
            $status = ['APPROVED', 'FAILED', 'PENDING', 'SUCCESS'];
            if ($this->params['status'] == 'OTHER') {
                $where[] = ['status', 'not in', $status];

            } else {
                $where[] = ['status', '=', $this->params['status']];
            }

        }


        //交易类型
        if (isset($this->params['transaction_type']) && $this->params['transaction_type']) {
            $transaction_type = ['AUTHORIZATION', 'CLEARING', 'REVERSAL'];
            if ($this->params['transaction_type'] == 'OTHER') {
                $where[] = ['transaction_type', 'not in', $transaction_type];
            } else {
                $where[] = ['transaction_type', '=', $this->params['transaction_type']];
            }

        }

        //商户类型
        if (isset($this->params['merchant_name']) && $this->params['merchant_name']) {
            $where[] = ['merchant_name', 'like', '%' . $this->params['merchant_name'] . '%'];
        }

        return $where;
    }

    /**
     * @notes 获取transaction列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2025/04/08 19:39
     */
    public function lists(): array
    {
        $list = TransactionRecord::where($this->searchWhere)
            ->field([
                'id', 'transaction_id', 'user_id', 'group_id', 'card_id', 'card_nickname',
                'masked_card_number', 'transaction_amount', 'transaction_currency',
                'service_fee', 'service_amount',
                'billing_amount', 'billing_currency', 'outbinservice', 'status', 'transaction_type', 'merchant_name', 'merchant_city',
                'merchant_country', 'merchant_category', 'auth_code', 'failure_reason',
                 'alias', 'matched_authorizations', 'transaction_date', 'posted_date', 'card_bin', 'smallamount', 'location_country'
            ])
            ->where($this->queryWhere())
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['transaction_date' => 'desc'])
            ->select()
            ->toArray();


        // 时区转换处理 - 只有在明确指定时区时才转换
        if (isset($this->params['timezone']) && !empty($this->params['timezone'])) {
            $timezone = $this->params['timezone'];
            foreach ($list as &$item) {
                if (!empty($item['transaction_date'])) {
                    try {
                        $utcTime = new \DateTime($item['transaction_date'], new \DateTimeZone('UTC'));
                        $utcTime->setTimezone(new \DateTimeZone($timezone));
                        $item['transaction_date'] = $utcTime->format('Y-m-d H:i:s');
                    } catch (\Exception $e) {
                        $item['transaction_date'] = $item['transaction_date'];
                    }
                }
            }
            unset($item);
        }
        return $list;


    }


    /**
     * @notes 获取transaction数量
     * @return int
     */
    public function count(): int
    {
        return TransactionRecord::where($this->searchWhere)->where($this->queryWhere())->count();
    }

    /**
     * @notes 扩展字段，目前只统计交易金额，不区分交易状态
     * @return array
     */
    public function extend()
    {
        // 交易记录总金额
        $billing_amount = TransactionRecord::where($this->searchWhere)
            ->where($this->queryWhere())
            ->whereIn('transaction_type', [
                'CARD_PAYMENT', 'CLEARING', 'settled', 'pending', 'AUTHORIZATION', 'WAITING_CLEARANCE'
            ])
            ->whereRaw("RTRIM(LTRIM(status)) IN ('SUCCESS', 'settled', 'posted', 'pending', 'CARD_PAYMENT', 'WAITING_CLEARANCE')")
            ->sum(Db::raw('ABS(billing_amount)'));

        return ['billing_amount' => $billing_amount];
    }

    public function setFileName(): string
    {
        return '交易记录';
    }

    /**
     * @notes 导出字段
     * @return string[]
     */
    public function setExcelFields(): array
    {
        return [
            'transaction_date' => '交易时间',
            'transaction_id' => '交易id',
            'card_id' => 'card_ID',
            'masked_card_number' => '卡号',
            'merchant_name' => '商户',
            'billing_amount' => '账单金额',
            'transaction_currency'=> '交易币种',
            'outbinservice' => '服务费',
            'transaction_type' => '交易类型',
            'status' => '交易状态',
            'card_bin' => '供应商',
            'group_id' => '客户',
            'alias' => '卡片别名',
            'location_country' => '交易地址',

        ];
    }

}